package com.hps.shoping.order.service.impl;

import com.alibaba.fastjson.JSON;
import com.hps.shoping.order.component.MessageProducer;
import com.hps.shoping.order.entitys.Order;
import com.hps.shoping.order.mapper.OrderMapper;
import com.hps.shoping.order.service.OrderService;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.text.DateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.UUID;

/**
 * @author heps
 * @date 2019/9/1 9:54
 */
@Service
public class OrderServiceImpl implements OrderService {

    private final OrderMapper orderMapper;

    private final MessageProducer messageProducer;

    public OrderServiceImpl(OrderMapper orderMapper, MessageProducer messageProducer) {
        this.orderMapper = orderMapper;
        this.messageProducer = messageProducer;
    }

    @Override
    public List<Order> findAll() {
        return orderMapper.selectAll();
    }

    @Override
    public boolean createOrder() {
        Order order = new Order();
        order.setId(UUID.randomUUID().toString());
        order.setCreatedTime(new Date());

        Random random = new Random();
        long goodId = 1 + random.nextInt(5);
        order.setGoodId(goodId);
        order.setStatus((byte) 0);

        orderMapper.insert(order);

        String orderStr = JSON.toJSONString(order);

        try {
            messageProducer.send(orderStr);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return true;
    }

    @Override
    public boolean updateStatus(String orderId, Byte status) {
        return orderMapper.updateStatus(orderId, status) > 0;
    }

    @Scheduled(cron = "*/30 * * * * *")
    public void retry() {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String nowStr = formatter.format(LocalDateTime.now());
        List<Order> orders = orderMapper.selectUnfinishOrders(nowStr);
        System.out.println(orders);
        if (!CollectionUtils.isEmpty(orders)) {
            for (Order order : orders) {
                String orderStr = JSON.toJSONString(order);

                try {
                    messageProducer.send(orderStr);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}
